﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Globalization;
using System.Net;

namespace SAP
{
    public partial class PurchaseRequisition : System.Web.UI.Page
    {
        public static DataTable dtContents;
        public static DataTable dtHeader;
        //private LoginSession CurrentLoginSession;
       // private GeneralFunctions GF;
         
        private string DocType = "";
        private string TblHeaderName = "";
        private string TblLineName = "";
        private string ObjType = "";

        public static string KeepColumsContent = "";
        private int EmpID = -1;
        private int Manager_EmpID = -1;
        private int RequestID = -1;
        private static int RequestType = 0;

    #region Functions

        protected void ClearScreen()
        {
            /*
            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);

            txtNo.Text = "";
            txtVendor.Text = "";
            txtName.Text = "";

            dtContents.Clear();
            SetScreenStatus("New");
            KeepColumsContent = GF.BuildKeepColumnStr(dtContents);
             * */
        }

        private void ResetLineNo()
        {
            int i = 0;
            foreach (DataRow row in dtContents.Rows)
            {
                i++;
                row["No"] = i;
                row["LineNum"] = i;
            }
        }

        private void SetControlsStatus(string asStatus)
        {
            switch (asStatus)
            {
                case "Add":
                    btnUpdate.Enabled = btnAdd.Enabled = btnAddRecord.Enabled = false;
                    break;
                case "Edit":
                     btnUpdate.Enabled =btnAdd.Enabled = btnAddRecord.Enabled = false;
                    break;
                case "Update":
                     btnUpdate.Enabled =btnAdd.Enabled = btnAddRecord.Enabled = true;
                    break;
                case "Save":
                     btnUpdate.Enabled =btnAdd.Enabled = btnAddRecord.Enabled = true;
                    break;
            }
            
        }

        public String _collectData()
        {
            try
            {
                
                //Update table header
                DataRow dr = dtHeader.Rows[0];

                CultureInfo ivC = new System.Globalization.CultureInfo("es-US");

                dr["DocDate"] = Convert.ToDateTime(txtPostingDate.Text, ivC).ToString("yyyyMMdd");
                dr["DocDueDate"] = Convert.ToDateTime(txtDueDate.Text, ivC).ToString("yyyyMMdd");
                dr["ReqDate"] = Convert.ToDateTime(txtDocumentDate.Text, ivC).ToString("yyyyMMdd");
                dr["OwnerCode"] = EmpID;
                dr["Requester"] = EmpID;
                dr["ReqName"] = txtName.Text;
                dr["ReqType"] = 171;//employee
                dr["Filler"] = lb_WhsCode.Text;
                dr["DefaultWhsName"] = txtFromWarehouse.Text;
                dr["U_UserID"] = User.Identity.Name;

                //dr["GroupNum"] = "1";

                switch (ddlRequisitionType.SelectedValue.ToString())
                {
                    case "F": //goods issue draf
                        DocType = "112";
                        TblHeaderName = "ODRF";
                        TblLineName = "DRF1";
                        if ( dtHeader.Columns.Contains("ObjType") ==false)
                        {
                            dtHeader.Columns.Add("ObjType");
                        }
                        dr["ObjType"] = "60";
                        break;
                    case "B": //transfer request
                        DocType = "1250000001";
                        TblHeaderName = "OWTQ";
                        TblLineName = "WTQ1";
                        break;
                    case "P": //purchase request
                        DocType = "1470000113";
                        TblHeaderName = "OPRQ";
                        TblLineName = "PRQ1";
                        break;

                }
                //Master.FindControl("theMenu")
                Array arrContentsCols = new string[] { "Quantity" }; // Columns need to reset format numeric


                return null; // objInfo.ToXMLStringFromDS(DocType, ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                              "Dialog.hideLoader();", true);
                return "";
            }
        }

        private void getDocumentInfo() {
            switch (ddlRequisitionType.SelectedValue.ToString())
            {
                case "F": //goods issue draf
                    DocType = "112";
                    TblHeaderName = "ODRF";
                    TblLineName = "DRF1";
                    ObjType = "60";
                    break;
                case "B": //transfer request
                    DocType = "1250000001";
                    TblHeaderName = "OWTQ";
                    TblLineName = "WTQ1";
                    break;
                case "P": //purchase request
                    DocType = "1470000113";
                    TblHeaderName = "OPRQ";
                    TblLineName = "PRQ1";
                    break;                
            }
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    btnAdd.Visible = true;
                    btnUpdate.Visible = false;
                    btnAddRecord.Visible = true;
                    btnSaveSubmit.Visible = true;
                    break;
                case "Update":
                    btnAdd.Visible = false;
                    btnUpdate.Visible = false;
                    btnAddRecord.Visible = false;
                    btnSaveSubmit.Visible = true;
                    break;
                case "Close":
                    btnAdd.Visible = false;
                    btnUpdate.Visible = false;
                    btnAddRecord.Visible = false;
                    btnSaveSubmit.Visible = false;
                    break;
            }
        }        

        private void _cancelAddNew()
        {
            this.lvContents.InsertItemPosition = InsertItemPosition.None;
            this.btnAddRecord.Enabled = true;
            this.lvContents.DataBind();
        }

        protected void LoadDefault()
        {
            this.txtStatus.Text = "Open";
            this.txtStatus.Enabled = false;
            this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDueDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtDocumentDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtNo.Text = "";
        }

        private string GetEmailList()
        {
            Transaction trx = new Transaction();
            DataSet ds = trx.GetMarketingDocument_ReturnDS("2", txtVendor.Text, User.Identity.Name);
            string emaillist = "";
            if (!string.IsNullOrEmpty(ds.Tables[0].Rows[0]["E_mail"].ToString()))
                emaillist = ds.Tables[0].Rows[0]["E_mail"].ToString();
            foreach (DataRow dr in ds.Tables[2].Rows)
            {
                if (dr["E_mailL"].ToString() != "")
                    emaillist = emaillist + "," + dr["E_mailL"].ToString();
            }

            return emaillist;
        }
        /*
         <asp:ListItem Text="Not Approve" Value="0"></asp:ListItem>
                                        <asp:ListItem Text="Approved" Value="1"></asp:ListItem>
                                        <asp:ListItem Text="Pending" Value="2"></asp:ListItem>
                                        <asp:ListItem Text="Posted to SAP" Value="3"></asp:ListItem>
         */
        private string getStatusName(string stCode) {
            if(stCode == "0")
                return "Rejected";
            if (stCode == "1")
                return "Approved";
            if (stCode == "2")
                return "Pending";
            if (stCode == "3")
                return "Draft";
            return "Unspecified";
        }
        public void SessionCheck()
        {

            if (Session["LoginSession"] != null)
            {
                //this.CurrentLoginSession = (LoginSession)Session["LoginSession"];
               // GF = new GeneralFunctions(CurrentLoginSession.UserName);
            }
            else
            {
                Response.Redirect("SessionErrorPage.aspx");
            }

        }    
    #endregion

    #region Event
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SessionCheck();
                GetDefault df = new GetDefault();
                DataTable dt = new DataTable();
               // dt = df.GetLoginInfo(CurrentLoginSession.UserName, 0).Tables[0];

                EmpID = (int)dt.Rows[0]["EmpID"];
                Manager_EmpID = (int)dt.Rows[0]["managerID"];//(int)(tblUser.Rows[0]["Manager_EmpID"].ToString() =="" ? -1 : tblUser.Rows[0]["Manager_EmpID"]);

                //this.RequestStatus = Request.QueryString["requestID"] == null ? -1 : Request.QueryString["requestID"]==""?-1:Int32.Parse (Request.QueryString["requestID"]);
                //isUpdate = 0;// Int32.Parse(Request.QueryString["isupdate"]); //update or addnew stock requisition 1: update, 0: add new
                //this.docEntry = 6;// Int32.Parse(Request.QueryString["docentry"]);
               
                //this.RequestID = Request.QueryString["requestID"] == ""?-1:Int32.Parse( Request.QueryString["requestID"]); // if 
                this.RequestID = Request.QueryString["requestID"] == null ? -1 : Request.QueryString["requestID"] == "" ? -1 : Int32.Parse(Request.QueryString["requestID"]); // if 
                
                if (!IsPostBack)
                {
                    
                    if (EmpID == 0)
                    {
                        Response.Redirect("PermissionDenied.aspx");
                    }
                   

                    if (RequestID != -1) //update
                    {
                        btnAdd.Visible = false;
                        /*
                        DataTable tbl = GF.ObjectSelect("usp_OffHeader_Select", "@hdrID", RequestID.ToString());

                        ddlRequisitionType.SelectedIndex = tbl.Rows[0]["ReqType"].ToString() == "F" ? 0 : (tbl.Rows[0]["ReqType"].ToString() == "B" ? 1 : (tbl.Rows[0]["ReqType"].ToString() == "P" ? 2 : 3));
                        lb_RequestType.Text = tbl.Rows[0]["ReqType"].ToString() == "F" ? "FOOD REQUEST" : (tbl.Rows[0]["ReqType"].ToString() == "B" ? "BEVERAGE REQUEST" : (tbl.Rows[0]["ReqType"].ToString() == "P" ? "PURCHASE REQUEST" : "FOOD TRANSFER"));
                        if (tbl.Rows[0]["ReqType"].ToString() == "F") {
                            //lb_FromWhs.Visible = false;
                            //txtFromWarehouse.Visible = false;
                            //hl_ChooseWhs.Visible = false;
                        }

                        if (tbl.Rows[0]["ReqType"].ToString() == "P") //Purchase Request
                        {
                            txt_ToWhs.Visible = false;
                            lb_ToWhsCode.Visible = false;
                            lb_ToWhs.Visible = false;
                            hl_ChooseToWhs.Visible = false;
                        }

                        if (tbl.Rows[0]["ReqType"].ToString() == "E")//Food transfer
                        {
                            btnSaveSubmit.Visible = false;
                        }
                        this.txtNo.Text = tbl.Rows[0]["hdrID"].ToString();
                        this.txtStatus.Text = getStatusName(tbl.Rows[0]["Status"].ToString());


                        this.txtName.Text = tbl.Rows[0]["ReqName"].ToString();
                        this.txtVendor.Text = tbl.Rows[0]["Requester"].ToString();
                        lb_WhsCode.Text = tbl.Rows[0]["Filler"].ToString();
                        txtFromWarehouse.Text = tbl.Rows[0]["DefaultWhsName"].ToString();

                        txtDocumentDate.Text = DateTime.Parse(tbl.Rows[0]["DocDate"].ToString()).ToString("dd/MM/yyyy");
                        txtDueDate.Text = DateTime.Parse(tbl.Rows[0]["DocDueDate"].ToString()).ToString("dd/MM/yyyy");
                        txtPostingDate.Text = DateTime.Parse(tbl.Rows[0]["ReqDate"].ToString()).ToString("dd/MM/yyyy");

                        txt_ToWhs.Text = tbl.Rows[0]["ToWhsName"].ToString();
                        lb_ToWhsCode.Text = tbl.Rows[0]["ToWhsCode"].ToString();

                        //2. detail
                        //dtContents = GF.ObjectSelect("usp_OffDetail_Select", "@hdrID", RequestID.ToString());//GF.ConvertDataTable_RemoveCols(, KeepColumsContent);
                        this.lvContents.DataSource = dtContents;
                        this.lvContents.DataBind();
                         * */
                    }
                    else //add new
                    {

                        //1. master
                        RequestType = Request.QueryString["requestType"] == null ? 0 : Int32.Parse (Request.QueryString["requestType"]);
                        ddlRequisitionType.SelectedIndex = RequestType;
                        this.lb_RequestType.Text = RequestType == 0 ? "FOOD REQUEST" : (RequestType == 1 ? "BEVERAGE REQUEST" : (RequestType == 2 ? "PURCHASE REQUEST" : "FOOD TRANSFER"));
                        
                        //if (RequestType == 3)//food transfer
                        //    btnSaveSubmit.Visible = false;
                        if (RequestType == 2) //food or purchase req
                        {
                            lb_ToWhsCode.Visible = false;
                            lb_ToWhs.Visible = false;
                            hl_ChooseToWhs.Visible = false;
                            txt_ToWhs.Visible = false;
                            //lb_FromWhs.Visible = false;
                            //txtFromWarehouse.Visible = false;
                            //hl_ChooseWhs.Visible = false;
                        }
                        string usrName = User.Identity.Name;

                        txtVendor.Text = EmpID.ToString();// tblUser.Rows[0]["UserName"].ToString();
                        txtName.Text = dt.Rows[0]["EmployeeName"].ToString();// tblUser.Rows[0]["LoweredUserName"].ToString();
                        txtFromWarehouse.Text = dt.Rows[0]["DefaultWhsName"].ToString();//tblUser.Rows[0]["DefaultWhs"].ToString();
                        lb_WhsCode.Text = dt.Rows[0]["U_DefaultWhs"].ToString();

                        txt_ToWhs.Text = dt.Rows[0]["DefaultWhsName"].ToString();
                        lb_ToWhsCode.Text = dt.Rows[0]["U_DefaultWhs"].ToString();

                        this.txtPostingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
                        this.txtDueDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
                        this.txtDocumentDate.Text = DateTime.Now.ToString("dd/MM/yyyy");


                        this.txtNo.Text = "";
                        this.txtStatus.Text = "Draft";
                        btnUpdate.Visible = false;

                       // dtContents = GF.RunQuery("select * from OffDetail where detID = -1");
                        lvContents.DataSource = dtContents;
                        lvContents.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {
               
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            /*
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    Int32 itemNo = 0;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "MultiItemsCallBack":
                            ArrayList chosenItems = Session["chosenItems"] as ArrayList;
                            DataRow drX;
                            int currNo = dtContents.Rows.Count + 1;

                            foreach (ItemMaster item in chosenItems) {
                                drX = dtContents.NewRow();
                                drX["ItemCode"] = item.ItemCode;
                                drX["Dscription"] = item.ItemName;
                                drX["Quantity"] = 1;
                                if (RequestType == 1) //beverage request
                                {
                                    drX["WhsCode"] = lb_ToWhsCode.Text;
                                    drX["WhsName"] = txt_ToWhs.Text;
                                }
                                else { 
                                    drX["WhsCode"] = lb_WhsCode.Text;
                                    drX["WhsName"] = txtFromWarehouse.Text;
                                }
                                drX["invntryuom"] = item.InvOUM;
                                drX["LineNum"] = drX["No"] = currNo++;
                                
                                dtContents.Rows.Add(drX);
                            }    
                            this.lvContents.DataSource = dtContents;
                            this.lvContents.DataBind();
                            break;

                        case "EditItemCallBack":
                            /*
                            ItemMaster chosenItem = Session["chosenItem"] as ItemMaster;
                            itemNo = Int32.Parse(Session["chosenItemNo"] as String);
                            if (chosenItem != null)
                            {   // update grid
                                dtContents.Rows[itemNo - 1]["ItemCode"] = chosenItem.ItemCode;
                                dtContents.Rows[itemNo - 1]["Dscription"] = chosenItem.ItemName;
                                dtContents.Rows[itemNo - 1]["Quantity"] = 1;
                                //RUK
                                if (RequestType == 1) //beverage request
                                {
                                    dtContents.Rows[itemNo - 1]["WhsCode"] = lb_ToWhsCode.Text;
                                    dtContents.Rows[itemNo - 1]["WhsName"] = txt_ToWhs.Text;
                                }
                                else //food, purchase, foodtransfer, return to warehouse
                                {
                                    dtContents.Rows[itemNo - 1]["WhsCode"] = lb_WhsCode.Text;
                                    dtContents.Rows[itemNo - 1]["WhsName"] = txtFromWarehouse.Text;
                                }
                                this.lvContents.DataSource = dtContents;
                                this.lvContents.DataBind();
                                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                         "Dialog.hideLoader();", true);
                            }
                             
                            break;
                        case "EditWareHouseCallBack":
                            WareHouse chosenWarehouse = Session["chosenWarehouse"] as WareHouse;
                            itemNo = Int32.Parse(Session["chosenItemNo"] as String);
                            if (chosenWarehouse != null)
                            {   
                                itemNo = Int32.Parse(Session["chosenItemNo"] as String);
                                if (itemNo == -1)
                                {
                                    lb_WhsCode.Text = chosenWarehouse.WhsCode;
                                    txtFromWarehouse.Text = chosenWarehouse.WhsName;
                                }
                                else if (itemNo == -2)
                                {
                                    lb_ToWhsCode.Text = chosenWarehouse.WhsCode;
                                    txt_ToWhs.Text = chosenWarehouse.WhsName;
                                }
                                else
                                {
                                    dtContents.Rows[itemNo - 1]["WhsCode"] = chosenWarehouse.WhsCode;
                                    dtContents.Rows[itemNo - 1]["WhsName"] = chosenWarehouse.WhsName;
                                    dtContents.Rows[itemNo - 1]["Quantity"] = ((TextBox)lvContents.Items[itemNo - 1].FindControl("txtQuantity")).Text;
                                    this.lvContents.DataSource = dtContents;
                                    this.lvContents.DataBind();
                                }
                            } break;                       
                        default:
                            
                            break;
                    }
                }
                     
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
             */
        }     
 
        protected void _btnAddRecord_Click(object sender, EventArgs e)
        {
            try
            {               
                int iNo = dtContents.Rows.Count + 1;
                dtContents.Rows.Add();
                dtContents.Rows[iNo-1]["No"] = iNo;
                dtContents.Rows[iNo - 1]["LineNum"] = iNo;
                this.lvContents.DataSource = dtContents;

                int lastpage = this.ProductListPagerCombo.TotalRowCount / this.ProductListPagerCombo.PageSize;
                this.ProductListPagerCombo.SetPageProperties(lastpage * this.ProductListPagerCombo.PageSize, this.ProductListPagerCombo.MaximumRows, false);
                this.lvContents.EditIndex = iNo - 1;
                this.lvContents.DataBind();
            }
            catch (Exception ex)
            {
                //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                //                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                //                                    "Dialog.hideLoader();", true);
            }
        }

        protected void lvContents_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                ListViewItem lvi = e.Item;
                switch (e.CommandName)
                {
                    case "CancelAddNew":
                        this._cancelAddNew();
                        this.lvContents.DataBind();
                        break;
                    case "CancelUpdate":
                        if (string.IsNullOrEmpty(((Label)lvi.FindControl("lblCode")).Text))
                        {
                            dtContents.Rows.RemoveAt(e.Item.DataItemIndex);
                            ResetLineNo();
                        }
                        this.lvContents.EditIndex = -1;
                        this.lvContents.DataSource = dtContents;
                        this.lvContents.DataBind();
                        //SetControlsStatus("Update");
                        break;
                    case "Update":
                        // update new data to dt
                        if (string.IsNullOrEmpty(((Label)lvi.FindControl("lblCode")).Text)) return;

                        Label lblNo = (Label)lvi.FindControl("lblNo");
                        foreach (DataRow row in dtContents.Rows)
                        {
                            if (row["No"].ToString().Equals(lblNo.Text)) // update currentrow into data table
                            {
                                row["ItemCode"] = ((Label)lvi.FindControl("lblCode")).Text;
                                row["Dscription"] = ((Label)lvi.FindControl("lblDescription")).Text;
                                row["Quantity"] = ((TextBox)lvi.FindControl("txtQuantity")).Text;
                                break;
                            }
                        }
                        this.lvContents.EditIndex = -1;
                        this.lvContents.DataSource = dtContents;
                        this.lvContents.DataBind();
                        break;

                    case "DeleteItem":
                        // delete data and update dt
                        int i_idx = e.Item.DataItemIndex;

                        string detID = dtContents.Rows[i_idx]["detID"].ToString() ;

                        dtContents.Rows.RemoveAt(i_idx);
                        this.lvContents.EditIndex = -1;
                        ResetLineNo();

                        if (detID != "") { 
                            //delete from DB, in case load to update
                            ArrayList arPar = new ArrayList();
                            arPar.Add("@detID");
                            ArrayList arVal = new ArrayList();
                            arVal.Add(detID);
                            //GF.ObjectUpdate("usp_OffDetail_Delete", arPar, arVal);
                            btnUpdate_Click(null, null);
                        }
                        this.lvContents.DataSource = dtContents;
                        this.lvContents.DataBind();
                        break;

                    default: break;
                }
            }
            catch (Exception ex)
            {
                //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                //                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                //ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                //                                    "Dialog.hideLoader();", true);
            }
        }

        protected void lvContents_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            /*
            try
            {
             
                this.lvContents.EditIndex = e.NewEditIndex;

                // Reset FormatNumeric 
                string lsQty = GF.ResetFormatNumeric(dtContents.Rows[e.NewEditIndex]["Quantity"].ToString());       // Quantity

                dtContents.Rows[e.NewEditIndex]["Quantity"] = lsQty;

                this.lvContents.DataSource = dtContents;
                this.lvContents.DataBind();
                //SetControlsStatus("Edit");
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
             * */
        }

        protected void lvContents_ItemInserted(object sender, ListViewInsertedEventArgs e)
        {
            this._cancelAddNew();
        }

        protected void imgbCancel_CancelAddNew(object sender, EventArgs e)
        {
            this.lvContents.DataSource = dtContents;
            this._cancelAddNew();
        }

        protected void lvContents_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            Label lblCode = (Label)lvContents.Items[e.ItemIndex].FindControl("lblCode");
            if (lblCode == null || string.IsNullOrEmpty(lblCode.Text))
            {
                e.Cancel = true;
                return;
            }
            this.lvContents.DataSource = dtContents;
            this.lvContents.DataBind();
        }

        protected void ProductListPagerCombo_PreRender(object sender, EventArgs e)
        {
            lvContents.DataSource = dtContents;
            lvContents.DataBind();
            
        }

        protected void btnAdd_Click(object sender, ImageClickEventArgs e)
        {
            /*
            try
            {

                //add header
                CultureInfo ivC = new System.Globalization.CultureInfo("es-US");
                string reqType = ddlRequisitionType.SelectedValue;
                int status = 3; //Save to draft
                getDocumentInfo();
                ArrayList param = new ArrayList();

                param.Add("@DocType");
				param.Add("@ReqType");
				param.Add("@Requester");
				param.Add("@ReqName");
				param.Add("@TaxDate");
				param.Add("@DocDate");
				param.Add("@DocDueDate");
				param.Add("@Comments");
				param.Add("@JrnlMemo");
				param.Add("@OwnerCode");
				param.Add("@Address");
				param.Add("@Address2");
				param.Add("@Project");
				param.Add("@LicTradNum");
				param.Add("@NumAtCard");
				param.Add("@ReqDate");
				param.Add("@Filler");
				param.Add("@U_UserID");
				param.Add("@DefaultWhsName");
				param.Add("@Manager_EmpID");
				param.Add("@EmpID");
				param.Add("@Status");

                param.Add("@TblHeaderName");
                param.Add("@TblLineName");
                param.Add("@ObjType");


                param.Add("@ToWhsCode");
                param.Add("@ToWhsName");

                ArrayList vals = new ArrayList();
                vals.Add(DocType);//DocType
                vals.Add(reqType);//ReqType
                vals.Add(EmpID);//Requester
                vals.Add(txtName.Text);//ReqName
                vals.Add(String.Format("{0:yyyyMMdd}", DateTime.ParseExact(txtDocumentDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)));
                vals.Add(String.Format("{0:yyyyMMdd}", DateTime.ParseExact(txtPostingDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)));
                vals.Add(String.Format("{0:yyyyMMdd}", DateTime.ParseExact(txtDueDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)));

                vals.Add("");//Comments
                vals.Add("");//JrnlMemo
                vals.Add(EmpID);//OwnerCode
                vals.Add("");//Address
                vals.Add("");//Address2
                vals.Add("");//Project
                vals.Add("");//LicTradNum
                vals.Add("");//NumAtCard
                vals.Add(String.Format("{0:yyyyMMdd}", DateTime.ParseExact(txtDocumentDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)));//ReqDate
                vals.Add(lb_WhsCode.Text);//Filler
                vals.Add(CurrentLoginSession.UserName);//U_UserID
                vals.Add(txtFromWarehouse.Text);//DefaultWhsName
                vals.Add(Manager_EmpID);//Manager_EmpID
                vals.Add(EmpID);//EmpID
                vals.Add(status);//Status

                vals.Add(TblHeaderName);//TblHeaderName
                vals.Add(TblLineName);//TblLineName
                vals.Add(ObjType);//ObjType

                vals.Add(lb_ToWhsCode.Text);
                vals.Add(txt_ToWhs.Text);

                this.RequestID = GF.ObjectUpdate("usp_OffHeader_Add", param, vals);
                if (RequestID != -1)//add header complete
                {
                    ArrayList par = new ArrayList();
                    par.Add("@hdrID");
					par.Add("@No");
					par.Add("@ItemCode");
					par.Add("@Dscription");
					par.Add("@Quantity");
					par.Add("@WhsCode");
					par.Add("@OcrCode");
					par.Add("@OcrCode2");
					par.Add("@OcrCode3");
					par.Add("@OcrCode4");
					par.Add("@OcrCode5");
					par.Add("@LineNum");
					par.Add("@invntryuom");
                    par.Add("@WhsName");
                    ArrayList val = new ArrayList();
                    foreach (DataRow dr in dtContents.Rows) {
                        val.Clear();
                        val.Add(RequestID);
                        val.Add(dr["No"]);
                        val.Add(dr["ItemCode"]);
                        val.Add(dr["Dscription"]);
                        val.Add(dr["Quantity"]);
                        val.Add(dr["WhsCode"]);
                        val.Add(dr["OcrCode"]);
                        val.Add(dr["OcrCode2"]);
                        val.Add(dr["OcrCode3"]);
                        val.Add(dr["OcrCode4"]);
                        val.Add(dr["OcrCode5"]);
                        val.Add(dr["LineNum"]);
                        val.Add(dr["invntryuom"]);
                        val.Add(dr["WhsName"]);
                        GF.ObjectUpdate("usp_OffDetail_Add", par, val);
                    }
                    dtContents.Clear();
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                "Dialog.hideLoader();", true);
                }
                else
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation error!" + "','');", true);
 
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
            */
        }

        protected void btnUpdate_Click(object sender, ImageClickEventArgs e)
        {
            /*
            try
            {
                ArrayList arrPar = new ArrayList();
                arrPar.Add("@detID");
                arrPar.Add("@No");
                arrPar.Add("@Quantity");
                arrPar.Add("@WhsCode");
                arrPar.Add("@LineNum");
                arrPar.Add("@WhsName");
                ArrayList arrVal = new ArrayList();
                foreach (DataRow dr in dtContents.Rows) {
                    if (dr.RowState == DataRowState.Modified) {
                        arrVal.Clear();
                        arrVal.Add(dr["detID"]);
                        arrVal.Add(dr["No"]);
                        arrVal.Add(dr["Quantity"]);
                        arrVal.Add(dr["WhsCode"]);
                        arrVal.Add(dr["LineNum"]);
                        arrVal.Add(dr["WhsName"]);
                        GF.ObjectUpdate("usp_OffDetail_Update", arrPar, arrVal);
                    }
                    else if (dr.RowState == DataRowState.Added) {
                        ArrayList par = new ArrayList();
                        par.Add("@hdrID");
                        par.Add("@No");
                        par.Add("@ItemCode");
                        par.Add("@Dscription");
                        par.Add("@Quantity");
                        par.Add("@WhsCode");
                        par.Add("@OcrCode");
                        par.Add("@OcrCode2");
                        par.Add("@OcrCode3");
                        par.Add("@OcrCode4");
                        par.Add("@OcrCode5");
                        par.Add("@LineNum");
                        par.Add("@invntryuom");
                        par.Add("@WhsName");
                        ArrayList val = new ArrayList();
                        val.Add(this.RequestID);
                        val.Add(dr["No"]);
                        val.Add(dr["ItemCode"]);
                        val.Add(dr["Dscription"]);
                        val.Add(dr["Quantity"]);
                        val.Add(dr["WhsCode"]);
                        val.Add(dr["OcrCode"]);
                        val.Add(dr["OcrCode2"]);
                        val.Add(dr["OcrCode3"]);
                        val.Add(dr["OcrCode4"]);
                        val.Add(dr["OcrCode5"]);
                        val.Add(dr["LineNum"]);
                        val.Add(dr["invntryuom"]);
                        val.Add(dr["WhsName"]);
                        GF.ObjectUpdate("usp_OffDetail_Add", par, val);
                    }
                }
                dtContents.AcceptChanges();
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                       "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                 "Dialog.hideLoader();", true);
               
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
             * */
        }

        protected void btnSaveSubmit_Click(object sender, ImageClickEventArgs e)
        {
            /*
            try
            {
                if (RequestID != -1) //update
                {
                    btnUpdate_Click(null, null);
                }
                else //add neww
                {
                    btnAdd_Click(null, null);                    
                }

                ArrayList param = new ArrayList();
                param.Add("@hdrID");
                ArrayList vals = new ArrayList();
                vals.Add(RequestID);
                GF.ObjectUpdate("usp_OffHeader_Submit", param, vals);
                dtContents.Clear();

                if (CurrentLoginSession.ManagerEmail != "")
                {
                    Emailling omail = new Emailling();
                    omail.SendMailNow(CurrentLoginSession.ManagerEmail, "Stock Requisition has been escalated for your approval", omail.GetTemplate_Submit(RequestID));
                }
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors",
                                                        "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ex.ToString()) + "','');", true);

                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading",
                                                    "Dialog.hideLoader();", true);
            }
             * */
        }

    #endregion      

        
        
    }
}